﻿using Enferno.StormApiClient;
using Enferno.StormApiClient.Expose;
using Enferno.StormApiClient.Expose.ErrorMessage_v2;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel;
using System.Web.Http.Filters;

namespace Enferno.Public.Web.Components.Server.ExceptionFilters
{
    public class ServiceModelFaultExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            var faultException = context.Exception as FaultException<ErrorMessage>;
            if (faultException == null) return;

            if (faultException.Detail.Record == null)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    ReasonPhrase = faultException.Message
                };
                return;
            }
            var message = faultException.Detail.Record.ToString().FromString<NameValues>().First();
            context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                ReasonPhrase = message.Value
            };
        }
    }
}
